package cn.chenc.framework.web.exception;


import cn.chenc.framework.core.exception.BaseException;
import cn.chenc.framework.core.exception.CustomException;
import cn.chenc.framework.core.exception.PreAuthorizeException;
import cn.chenc.framework.core.model.response.CommonCode;
import cn.chenc.framework.core.model.response.ResponseResult;
import cn.chenc.framework.core.model.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author secret
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    //捕获Exception异常
    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception e) {
        LOGGER.error("catch exception : {}\r\nexception: ",e.getMessage(), e);
        ResponseResult responseResult = new ResponseResult(CommonCode.SERVER_ERROR);
        return responseResult;
    }

    @ExceptionHandler(BaseException.class)
    public ResponseResult exception(BaseException e) {
        LOGGER.error("catch exception : {}\r\nexception: ",e.getMessage(), e);
        ResponseResult responseResult = ResponseResult.error(e.getMessage());
        return responseResult;
    }


    /**
     * NoHandlerFoundException 异常捕获处理
     * @param exception 自定义FileNotFoundException异常类型
     * @return ResponseResult
     */
    @ExceptionHandler({ NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseResult notFoundException(Exception exception) {
        return new ResponseResult(CommonCode.NOTFOUND);
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(PreAuthorizeException.class)
    public ResponseResult preAuthorizeException(PreAuthorizeException e) {
        return new ResponseResult(CommonCode.UNAUTHORISE);
    }


    //捕获 CustomException异常
    @ExceptionHandler(CustomException.class)
    public ResponseResult customException(CustomException e) {
        LOGGER.error("catch exception : {}\r\nexception: ",e.getMessage(), e);
        ResultCode resultCode = e.getResultCode();
        ResponseResult responseResult = new ResponseResult(resultCode);
        return responseResult;
    }



}
